import { createRouter, createWebHistory } from 'vue-router'

const routes = [
    {
        path: '/',
        name: 'Home',
        component: () => import('@/views/Home.vue'),
        meta: { requiresAuth: true }
    },
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/auth/Login.vue'),
        meta: { requiresAuth: false }
    },
    {
        path: '/403',
        name: 'Forbidden',
        component: () => import('@/views/error/403.vue'),
        meta: { requiresAuth: false }
    },
    {
        path: '/test-reset-password',
        name: 'TestResetPassword',
        component: () => import('@/views/auth/ResetPassword.vue'),
        meta: { requiresAuth: false } // 明确不需要认证
    }
]

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes
})

router.beforeEach(async (to, from, next) => {
    const userStore = useUserStore()

    // 初始化用户状态
    if (!userStore.isInitialized && to.meta.requiresAuth !== false) {
        try {
            await userStore.initialize()
        } catch (error) {
            console.error('用户状态初始化失败:', error)
        }
    }

    // 需要认证的路由
    if (to.meta.requiresAuth) {
        if (!userStore.isLoggedIn) {
            return next({
                path: '/login',
                query: { redirect: to.fullPath }
            })
        }

        if (to.meta.roles && !to.meta.roles.includes(userStore.user.role)) {
            return next('/403')
        }
    }

    next()
})

export default router